import React from 'react';
import {FlatList, Image, StyleSheet, Text} from 'react-native';
import {TouchableOpacity, View, Button} from 'react-native-ui-lib';
import {commonStyles} from '../../configs/commonStyle';
import BasePage from '../BasePage';
import ListEmpty from '../common/ListEmpty';
import DateFilter from '../components/DateFilter';
import {inject, observer} from 'mobx-react';
import moment from 'moment';
import PartsAbnormalDialog from './components/PartsAbnormalDialog';
import {getPartsList, disposeParts} from '../../net/transfer';
import {setClipboardContent} from '../../utils/util';
import ConfirmDialog from '../common/ConfirmDialog';
import ToastUtils from '../../utils/ToastUtils';
import PickerTypeDialog from '../common/PickerTypeDialog';
import {Icon} from '../components';

const pickerData = ['未处理', '已处理'];

@inject('userStore', 'appStore')
@observer
export default class TransferParts extends BasePage {
  constructor(props) {
    super(props);
    this.isLoading = false;
    this.takeItem = {};
    this.state = {
      isRefreshing: false,
      showEmpty: false,
      dataList: [],
      timeStart: moment().format('YYYY-MM-DD'),
      timeEnd: moment().format('YYYY-MM-DD'),
      status: '0',
    };
  }

  componentDidMount() {
    this.loadData();
  }

  loadData() {
    this.getPartsList();
    if (this.props.getUnDisposePartsCount) {
      const {timeStart, timeEnd} = this.state;
      this.props.getUnDisposePartsCount({
        timeStart: `${timeStart} 00:00:00`,
        timeEnd: `${timeEnd} 23:59:59`,
      });
    }
  }

  getPartsList = () => {
    const {timeStart, timeEnd, status} = this.state;
    this.isLoading = true;
    getPartsList({
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
      status,
      showLoading: true,
    })
      .then(res => {
        this.setState({
          dataList: (res.result && res.result.content) || [],
          isRefreshing: false,
          showEmpty: IsNullOrEmpty(res.result && res.result.content),
        });
      })
      .finally(() => {
        this.isLoading = false;
      });
  };

  take(item) {
    this.takeItem = item;
    this.confirmDialog.show(
      `请确认是否带走【${item.goodsName}-${item.xmbzNo}】?`,
    );
  }

  // 带走
  handleTake() {
    const {userInfo} = this.props.userStore;
    disposeParts({
      id: this.takeItem.id,
      orderId: this.takeItem.orderId,
      orderDetailId: this.takeItem.orderDetailId,
      remark: `${userInfo.name}: 带走`,
      goodsName: this.takeItem.goodsName,
    })
      .then(res => {
        ToastUtils.showSuccessInfo('带走成功');
        this.loadData();
      })
      .catch(err => {
        ToastUtils.showFailInfo(err?.msg || '失败，请重试');
      });
  }

  // 下拉刷新
  _renderRefresh = () => {
    // 不处于 下拉刷新
    if (this.isLoading === false) {
      this.loadData();
    }
  };

  render_item = ({item, index}) => {
    return (
      <View>
        <View
          style={{
            ...styles.titleWrap,
            backgroundColor: item.remark ? '#F9D63B' : '#b2bec3',
          }}>
          <TouchableOpacity
            flex
            activeOpacity={1}
            onPress={() => setClipboardContent(item?.xmbzNo)}>
            <Text>
              {item.goodsName}（{item.xmbzNo}）
            </Text>
          </TouchableOpacity>
          <View row>
            <Button
              style={{width: 60, backgroundColor: '#e74c3c', marginRight: 5}}
              color="#fff"
              size="xsmall"
              label="异常"
              onPress={() => this.partsAbnormalDialog.show({dataInfo: item})}
            />
            <Button
              style={{width: 60, backgroundColor: '#74b9ff'}}
              color="#fff"
              size="xsmall"
              label="带走"
              onPress={() => this.take(item)}
            />
          </View>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理内容</Text>
            <Text>{item.remark}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>配送开始时间</Text>
            <Text style={commonStyles.text_black_13}>
              {item.deliveryStartTime
                ? moment(item.deliveryStartTime).format('YYYY-MM-DD HH:mm:ss')
                : '-'}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>配送结束时间</Text>
            <Text style={commonStyles.text_black_13}>
              {item.deliveryEndTime
                ? moment(item.deliveryEndTime).format('YYYY-MM-DD HH:mm:ss')
                : '-'}
            </Text>
          </View>
        </View>
      </View>
    );
  };

  render() {
    const {dataList, isRefreshing, status} = this.state;
    return (
      <View
        useSafeArea
        style={{...commonStyles.body_primary, marginBottom: 32}}>
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter
              onQueryClick={(timeStart, timeEnd) =>
                this.setState(
                  {
                    timeStart,
                    timeEnd,
                  },
                  () => this._renderRefresh(),
                )
              }
            />
            <TouchableOpacity
              activeOpacity={1}
              style={styles.typeWrap}
              onPress={() =>
                this.pickerOrderTypeDialog.show(status, pickerData)
              }>
              <View marginR-3>
                <Text numberOfLines={1} style={commonStyles.text_black}>
                  {pickerData[status]}
                </Text>
              </View>
              <Icon type="AntDesign" name="down" size={12} color={'#CCCCCC'} />
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={1}
              throttleTime={1000}
              style={styles.btn}
              onPress={() => this._renderRefresh()}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{flexGrow: 1}}
            keyExtractor={(item, index) => 'menu_' + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => (
              <ListEmpty showEmpty={this.state.showEmpty} />
            )}
          />
        </View>

        <PickerTypeDialog
          ref={r => (this.pickerOrderTypeDialog = r)}
          onChecked={status => {
            this.setState({status});
          }}></PickerTypeDialog>
        <ConfirmDialog
          ref={r => (this.confirmDialog = r)}
          callBack={() => this.handleTake()}
        />
        <PartsAbnormalDialog
          ref={r => (this.partsAbnormalDialog = r)}
          callback={() => this.loadData()}></PartsAbnormalDialog>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: '#F9D63B',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
  },
  itemWrap2: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    paddingVertical: 6,
  },
  line: {
    height: 1,
    backgroundColor: '#EFEFEF',
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
  typeWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 90,
    height: 40,
    justifyContent: 'space-between',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    paddingHorizontal: 10,
    backgroundColor: 'white',
    marginRight: 10,
  },
});
